<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportToExcel">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img :src="scope.row.staffPhoto" width="100px" height="100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template #default="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="280"
          >
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-sizes="[2, 3, 5, 7]"
            :page-size="size"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增或者编辑 -->
      <el-dialog :visible.sync="showDialog" title="新增或者编辑" @close="hClose">
        <addOrEdit ref="addOrEdit" @maxpage="hMaxPage" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog
        :visible.sync="showDialogRole"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assignRole v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignRole from './assignRole.vue'
import addOrEdit from './empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import dayjs from 'dayjs'
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
//   console.log(hireType[1], 'hireType')
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  console.log(acc, 'acc')
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addOrEdit,
    assignRole // 分配角色
  },
  data() {
    return {
      // 省略其他 ...
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false, // 控制角色弹层的显示和隐藏
      showDialog: false, // 控制弹层的显示和隐藏
      page: 1, // 页码值
      size: 2, // 每页的条数
      list: [],
      total: 0
    }
  },
  created() {
    this.loadEmployessList()
  },
  methods: {
    hAssignRole(id) {
      this.showDialogRole = true
      this.curEmployeId = id
    },
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) {
        //   list中没有数据
        return
      }
      console.log(Object.keys(one))
      // 使用对象生成需要的header数据
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      console.log(header)

      const data = list.map(item => {
        //    item['formOfEmployment'] ====> 1 或者 2
        // hireType===> {1:'正式',2:'非正式'}
        item['formOfEmployment'] = hireType[ item['formOfEmployment']] || '未知'
        item['correctionTime'] = item['correctionTime'] || '-'
        return Object.values(item)
      })

      return { header, data }
    },
    async exportToExcel() {
      const res = await getEmployeeList(this.page, this.size)
      console.log(res.data.rows, 'getEmployeeList')
      const { header, data } = this.formData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      this.$refs.addOrEdit.resetForm()
    },
    formatDate(timer) {
      return dayjs(timer).format('YYYY-MM-DD')
    },
    hMaxPage() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // this.loadEmployees()
    },
    hSuccess() {
      this.showDialog = false
      this.loadEmployessList()
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 如果删除第最后一页（例如4）的最一条数据之后，页面会显示不正常
        if (this.employees.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployee()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployessList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployessList()
    },
    formOfEmploymentFormat(val) {
      // const result = employeesEnum.hireType.find(item => item.id === val)
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return hireType[val] ? hireType[val] : '未知'
    },

    async loadEmployessList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res, 'getEmployeeList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
